#coding=utf-8
#
import os
import json
import sys
import pymysql
import time

import yaml

import loggers
from mailthon import postman, email
import mailsender
import utils



#mailsender
p = postman(host='smtp.qq.com', auth=('aemaeth@foxmail.com', 'frightene99'))

#load yaml
data = yaml.load(open('config.yaml', 'r'))

#current dir
base_dir = os.path.abspath(os.path.dirname(sys.argv[0]))



#########################################################################################################

"""

Project Name

"""

currentlist = ["edyd", "edyd-customer", "edyd-intranet"]


"""

Project Name

"""



#########################################################################################################



for current in currentlist:
    try:
        currentData = data['projectRoot'][current]
        dbName = currentData['dbName']
        dbType = currentData['dbType']
        url = currentData['url']
        Port = currentData['Port']
        usrName = currentData['usrName']
        Pwd = currentData['Pwd']
        to = 20

        path = base_dir + '/sqlScript/' + current

        print('projectName:  '+current, '\ndbName:      ', dbName, '\ndbType:      ', dbType, '\nurl:         ', url, '\nusrName:     ', usrName, '\nPwd:         ', Pwd, '\nPort:        ',Port)
        print('\nBaseDir:      ' + base_dir)
        print('ScriptPath:   ' + path)
    except Exception as e:
            log.error()
            mailsender.mSender(repr(e))
            exit()


    if __name__=='__main__':
        log = loggers.LOG(time.strftime("%Y%m%d"))
        try:
            conn = pymysql.connect(host=url, user=usrName, password=Pwd, db=dbName, port=Port, charset="utf8", connect_timeout=to)
            cur = conn.cursor()
        except Exception as e:
            log.error()
            mailsender.mSender(repr(e))
            exit()

    with open('records.json', 'r+') as last:
        try:
            d = json.loads(last.read())
            # print(d)
        except:
            d = {}

    #list dir
    print('\n============    Listing .sql    ============\n')

    filelist = []

    for fi in os.listdir(path):

        #.sql filter
        if os.path.splitext(fi)[1] == '.sql':
            file = os.path.join(path, fi)

            if (not (fi in d.keys())) or (time.ctime(os.path.getmtime(file)) != d[fi]):

                print(file)
                filelist.append(file)
            elif time.ctime(os.path.getmtime(file) == d[fi]):
                pass

    for f in filelist:
        with open(f, 'r')as ff:
            sql = ff.read().replace("\n", " ")
            if sql.strip():

                try:
                    cur.execute(sql)

                except Exception as e:
                    log.error()
                    mailsender.mSender(repr(e))
                    # sql = ff.read().replace("\n", " ")
                    # try:
                    #     cur.execute(sql)
                    # except Exception as e:
                    #     log.error()
    # for f in filelist:
    #
    #     for line in open(f).read().split(';\n'):
    #         line = line.replace('//', '//')
    #         #\n filter
    #         if line.strip():
    #             print(line)
    #             try:
    #                 cur.execute(line)
    #             except Exception as e:
    #                 log.error()
    #                 mailsender.mSender(repr(e))
    #                 exit()
    #

            with open('records.json', 'w+') as now:
                d[f] = time.ctime(os.path.getmtime(f))
                try:
                    now.write(json.dumps(d))
                except Exception as e:
                    log.error()
                    mailsender.mSender(repr(e))
                    exit()

    print('\n============     List ended     ============\n')

    try:
        conn.commit()
    except Exception as e:
        log.error()
        mailsender.mSender(repr(e))
        exit()

    cur.close()
    conn.close()

log.info("\n\n\n*****************     finished without error     *****************")